package com.java.File;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileUse {
    // 整个文件系统中查找文件，支持相似查找
    public static List<File> searchFilesInSystem(String fileName) throws Exception {
        File[] listRoots = File.listRoots();
        
        List<File> resultFiles = new ArrayList<>();
        for (File listRoot : listRoots) {
            resultFiles = Stream.concat(resultFiles.stream(), searchFilesInPath(listRoot.getPath(), fileName).stream()).collect(Collectors.toList());
        }
        return resultFiles;
    }
    
    // 根据文件名在指定路径中相似查找文件，路径必须为文件夹路径
    public static List<File> searchFilesInPath(String path, String fileName) throws Exception {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            throw new Exception("路径错误，请检查路径是否存在或正确。错误路径为" + file.getPath());
        }
        
        File[] childFiles = file.listFiles();
        if (childFiles == null || childFiles.length == 0) {
            return null;
        }
        
        List<File> resultFiles = new ArrayList<>();
        for (File childFile : childFiles) {
            if (!childFile.isDirectory()) {
                if (childFile.getName().contains(fileName)) {
                    resultFiles.add(childFile);
                }
                continue;
            }
            
            List<File> resultChildFiles = searchFilesInPath(childFile.getPath(), fileName);
            if (resultChildFiles != null) {
                resultFiles = Stream.concat(resultFiles.stream(), resultChildFiles.stream()).collect(Collectors.toList());
            }
        }
        return resultFiles;
    }
    
    // 根据指定路径删除所有能删除的文件或文件夹，包括本身
    public static void deleteFileOrDir(String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            throw new Exception("路径错误，请检查路径是否存在。错误路径为" + file.getPath());
        }
        
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                if (!childFile.isDirectory()) {
                    childFile.delete();
                    continue;
                }
                
                deleteFileOrDir(childFile.getPath());
            }
        }
        
        file.delete();
    }
    
    public static void main(String[] args) throws Exception {
        String findFilePath = "File和IO流\\com\\java";
        String findFileFileName = "students";
        searchFilesInPath(findFilePath, findFileFileName).stream().map(File::getPath).forEach(System.out::println);
        searchFilesInSystem(findFileFileName).stream().map(File::getPath).forEach(System.out::println);
        
        String deleteFilePath = "File和IO流\\com\\java\\files\\delete\\del";
        deleteFileOrDir(deleteFilePath);
    }
}
